package org.example.servicelogin.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MqConfirmConfig implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);

        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                log.info("消息发送失败, Message:{}, Exchange:{}, ReplyCode:{}, ReplyTest:{}, RoutingKey:{}",
                        returnedMessage.getMessage(), returnedMessage.getExchange(), returnedMessage.getReplyCode(),
                        returnedMessage.getReplyText(), returnedMessage.getRoutingKey());
            }
        });

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack) {
                if (correlationData != null) {
                    log.info("消息发送成功, MessageId:{}", correlationData.getId());
                } else {
                    log.info("消息发送成功, MessageId: null");
                }
            } else {
                if (correlationData != null) {
                    log.info("消息发送失败, MessageId:{}, Cause:{}", correlationData.getId(), cause);
                } else {
                    log.info("消息发送失败, MessageId: null, Cause:{}", cause);
                }
            }
        });
    }
}